package com.example.smartagriculture.utils;

import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class FFmpegService {
    private Process process;
    private final String outputDir = "./hls-output/";

    public void startTranscode(String streamId) throws IOException {
        String rtspUrl = "rtsp://admin:CIC-Senior@172.16.76.225/Streaming/Channels/101";
        String outputPath = outputDir + streamId + ".m3u8";

        new File(outputDir).mkdirs(); // 创建输出目录

        ProcessBuilder pb = new ProcessBuilder(
                "ffmpeg",
                "-rtsp_transport", "tcp",
                "-i", rtspUrl,
                "-c:v", "copy",
                "-c:a", "aac",
                "-f", "hls",
                "-hls_time", "4",
                "-hls_list_size", "6",
                "-hls_flags", "delete_segments",
                outputPath
        );

        process = pb.start();
    }

    public void stopTranscode() {
        if (process != null && process.isAlive()) {
            process.destroy();
        }
    }
}
